 //
//  easyflyNetWork.m
//  easyflyDemo
//
//  Created by dukai on 15/5/26.
//  Copyright (c) 2015年 杜凯. All rights reserved.
//

#import "CrazyNetWork.h"
#import "JKToast.h"
#import "SVProgressHUD.h"
#import "TMMemoryCache.h"
#import "TMCache.h"
#import "CrazyFunction.h"


static CrazyNetWork * NetWork = nil;
@implementation CrazyNetWork

+(CrazyNetWork *)share{
    
    NetWork =[[CrazyNetWork alloc]init];
    
    return NetWork;
}

-(AFHTTPSessionManager *)create{
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    securityPolicy.allowInvalidCertificates = YES;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer.timeoutInterval = requstTimeOut;
    
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/json"];
    
    manager.securityPolicy = securityPolicy;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    return manager;
}

//网络请求
+(CrazyNetWork *)CrazyRequest_Get:(NSString *)header parameters:(NSDictionary *)parameters HUD:(BOOL)hud success:(requestSuccess)success fail:(requestFail)fail{
    
    if (hud){
       [CrazyNetWork CrazyShowHUD];
    }
    
    
    CrazyNetWork * request = [CrazyNetWork share];
    
    request.manager = [request create];
    request.block_fail = fail;
    request.block_success = success;
    
    [request.manager GET:header parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
        if (request.block_Progress) {
            request.block_Progress(downloadProgress);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString * json = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                  options:NSJSONReadingMutableContainers
                                                    error:nil];
        
        NSString *url = [task.originalRequest.URL absoluteString];
        
        request.block_success(dic,url,json);
        
        [CrazyNetWork CrazyHiddenHUD];

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
            if (request.block_fail) {
                request.block_fail(error,[task.originalRequest.URL absoluteString]);
                
                [CrazyNetWork CrazyHiddenHUD];
                [JKToast showWithText:@"网络访问失败"];
            }
            
        }];
    
   return request ;
}

//post 请求大数据量信息
+(CrazyNetWork *)CrazyRequest_Post:(NSString *)header parameters:(NSDictionary *)parameters HUD:(BOOL)hud success:(requestSuccess)success fail:(requestFail)fail{
    
    if (hud) {
        [CrazyNetWork CrazyShowHUD];
    }
    
    CrazyNetWork * request = [CrazyNetWork share];
    
    request.manager = [request create];
    request.block_fail = fail;
    request.block_success = success;
    
    [request.manager POST:header parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (request.block_Progress) {
            request.block_Progress(uploadProgress);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString * json = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSDictionary * dic = [CrazyFunction crazy_JsonStringToObject:json];
        
        request.block_success(dic,[task.originalRequest.URL absoluteString],json);
        
        [CrazyNetWork CrazyHiddenHUD];

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [JKToast showWithText:@"网络访问失败"];
        
        request.block_fail(error,[task.originalRequest.URL absoluteString]);
        
        [CrazyNetWork CrazyHiddenHUD];

    }];
    
    return request;
}


//文件流上传
+(CrazyNetWork *)CrazyHttpFileUpload:(NSString *)headUrl imageDic:(NSDictionary *)imageDic HUD:(BOOL)hud block:(requestSuccess)success fail:(requestFail)fail{
    
    if (hud) {
         [CrazyNetWork CrazyShowHUD];
    }
    CrazyNetWork * network = [CrazyNetWork share];
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:headUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        for (int i = 0; i<imageDic.allKeys.count; i++) {
            NSString *key = imageDic.allKeys[i];
            UIImage *image = imageDic[key];
            NSData *imageData= UIImageJPEGRepresentation(image, 100);
            [formData appendPartWithFileData:imageData name:key fileName:[NSString stringWithFormat:@"%d",i] mimeType:@"image/jpeg"];
        }
        
    } error:nil];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.timeoutIntervalForResource = uploadTimeOut;
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (network.block_Progress) {
            network.block_Progress(uploadProgress);
        }
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (error) {
            
            fail(error,[response.URL absoluteString]);
            [CrazyNetWork CrazyHiddenHUD];
        } else {
            
            success(responseObject,[response.URL absoluteString],@"");
            [CrazyNetWork CrazyHiddenHUD];
        }
    }];
    
    [uploadTask resume];
    
    return network;

}
//base64上传
+(CrazyNetWork *)CrazyHttpBase64Upload:(NSString *)headUrl imageDic:(NSDictionary *)imageDic parameters:(NSDictionary *)parameters HUD:(BOOL)hud block:(requestSuccess)success fail:(requestFail)fail{
    
    NSMutableDictionary *postDic = [[NSMutableDictionary alloc]init];
    for (int i = 0; i<imageDic.allKeys.count; i++) {
        
        NSString *key = imageDic.allKeys[i];
        UIImage *image = imageDic[key];
        
        NSData* imageData = UIImageJPEGRepresentation(image, 100);
        NSString *strBase64 = [imageData base64EncodedStringWithOptions:0];
        
        [postDic setObject:strBase64 forKey:key];
    }
    
    for (int i = 0; i<parameters.allKeys.count; i++) {
        
        NSString *key = parameters.allKeys[i];
        UIImage *value = parameters[key];

        [postDic setObject:value forKey:key];
    }
    
   CrazyNetWork *request =  [CrazyNetWork CrazyRequest_Post:headUrl parameters:postDic HUD:hud success:^(NSDictionary *dic, NSString *url,NSString *Json) {
       
       success(dic,url,Json);
       
   } fail:^(NSError *error, NSString *url) {
       fail(error,url);
   }];
    
    return request;

}

//网络缓存请求
+(void)CrazyRequestCache_Get:(NSString *)header parameters:(NSDictionary *)parameters HUD:(BOOL)hud success:(requestSuccess)success fail:(requestFail)fail{
    NSString *requestUrl = [CrazyNetWork requestURl:header parameters:parameters];
    [[TMCache sharedCache]objectForKey:requestUrl block:^(TMCache *cache, NSString *key, id object) {
        NSDictionary * dic = (NSDictionary *)object;
        if (dic.allKeys >0) {
            success(dic,requestUrl,@"");
        }else{
            [CrazyNetWork CrazyShowHUD];
            
            [CrazyNetWork CrazyRequest_Get:header parameters:parameters HUD:hud success:^(NSDictionary *dic, NSString *url,NSString *Json) {
                [[TMCache sharedCache]setObject:dic forKey:requestUrl];
                success(dic,url,Json);
                [CrazyNetWork CrazyHiddenHUD];
                
            } fail:^(NSError *error, NSString *url) {
                
                [CrazyNetWork CrazyHiddenHUD];
                [JKToast showWithText:@"网络访问失败"];
                fail(error,url);
            }];
        }
    }];
    
}

//网络POST缓存请求  大数据量
+(void)CrazyRequestCache_Post:(NSString *)header parameters:(NSDictionary *)parameters HUD:(BOOL)hud success:(requestSuccess)success fail:(requestFail)fail{
    
    NSString *requestUrl = [CrazyNetWork requestURl:header parameters:parameters];
    
    [[TMCache sharedCache]objectForKey:requestUrl block:^(TMCache *cache, NSString *key, id object) {
        NSDictionary * dic = (NSDictionary *)object;
        if (dic.allKeys >0) {
            success(dic,requestUrl,@"");
        }else{
            
            [CrazyNetWork CrazyRequest_Post:header parameters:parameters HUD:hud success:^(NSDictionary *dic, NSString *url,NSString *Json) {
                [[TMCache sharedCache]setObject:dic forKey:requestUrl];
                
                success(dic,url,Json);
                [CrazyNetWork CrazyHiddenHUD];
                
            } fail:^(NSError *error, NSString *url) {
                fail(error,url);
            }];
        }
    }];
    
}
+(void)CrazyRequestCache_removeKey:(NSString *)key{
    [[TMCache sharedCache]removeObjectForKey:key];
}
+(void)CrazyRequestCache_removeAll{
    [[TMCache sharedCache]removeAllObjects];
}


+(NSString *)requestURl:(NSString*)header parameters:(NSDictionary *)parameters{
    if (parameters.allKeys == 0 && parameters == nil) {
        return header;
    }else {
        NSMutableString *requstStr = [[NSMutableString alloc]initWithString:header];
        [requstStr appendString:@"?"];
        NSArray * keys = parameters.allKeys;
        for (int i = 0 ; i < keys.count; i++) {
            NSString *key  = keys[i];
            [requstStr appendFormat:@"%@=%@&",key,parameters[key]];
        }
        [requstStr deleteCharactersInRange:NSMakeRange(requstStr.length -1, 1)];
        
        return requstStr;
    }
}

+(void)CrazyShowHUD{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD show];
    });
    
}
+(void)CrazyHiddenHUD{
    
   [SVProgressHUD dismiss];
}


@end
